<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Admin\View\Helper;

use Admin\Data\Common;
use Admin\Data\Config;
use Laminas\Config\Factory;
use Laminas\Math\Rand;
use Laminas\Mvc\I18n\Translator;
use Laminas\Session\Container;
use Laminas\View\Helper\AbstractHelper;

class AdminHelper extends AbstractHelper
{
    private $translator;
    private $request;
    private $sessionAdmin;
    private $routeMatch;
    private $csrfValue = '';

    public function __construct(
        Translator      $translator,
        $request,
        $routeMatch
    )
    {
        $this->translator       = $translator;
        $this->request          = $request;
        $this->routeMatch       = $routeMatch;

        if($this->sessionAdmin == null) $this->sessionAdmin = new Container('dbshopAdmin');
    }

    /**
     * session的管理员信息
     * @param $adminField
     * @return mixed
     */
    public function admin($adminField)
    {
        return $this->sessionAdmin->offsetGet($adminField);
    }

    /**
     * 通用有效时间计算
     * @param $startTime
     * @param $endTime
     * @return string
     */
    public function effectiveTime($startTime, $endTime)
    {
        $iStartTime  = $startTime > 0 ? $this->getView()->dateFormat($startTime, \IntlDateFormatter::MEDIUM, \IntlDateFormatter::NONE, Config::SHOP_DATE_FORMAT) : '';
        $iEndTime    = $endTime > 0 ? $this->getView()->dateFormat($endTime, \IntlDateFormatter::MEDIUM, \IntlDateFormatter::NONE, Config::SHOP_DATE_FORMAT) : '';
        if(empty($iStartTime) && empty($iEndTime)) {
            $startAndEndTime = $this->translator->translate('长期有效');
        } elseif (!empty($iEndTime) && time() > $endTime) {
            $startAndEndTime = '<label class="text-red">'.$this->translator->translate('已经过期').'</label>';
        } else {
            $startAndEndTime = (empty($iStartTime) ? $this->translator->translate('无') : $iStartTime) . ' / ' . (empty($iEndTime) ? $this->translator->translate('无') : $iEndTime);
        }

        return $startAndEndTime;
    }

    /**
     * 创建get操作的CSRF Token
     * @return string
     */
    public function getCsrfValue()
    {
        if(empty($this->csrfValue)) {
            $this->sessionAdmin->offsetSet('queryToken', md5(time() . Rand::getBytes(32) . 'queryToken'));
            $this->csrfValue = $this->sessionAdmin->offsetGet('queryToken');
        }
        return $this->csrfValue;
    }

    /**
     * 返回分页url的Query字符串，去除page
     * @return bool|string
     */
    public function pagesQuery()
    {
        $queryStr = $this->request->getServer()->get('QUERY_STRING');
        if(!empty($queryStr)) {
            if(strpos($queryStr, 'page=') !== false) {
                $num = strpos($queryStr, '&');
                if($num) return substr($queryStr, $num);
                else return '';
            } else return '&'.$queryStr;
        }
        return $queryStr;
    }

    public function getRoute()
    {
        if($this->routeMatch == null) return false;

        return $this->routeMatch->getMatchedRouteName();
    }

    public function getModule()
    {
        if($this->routeMatch == null) return false;

        $controller = $this->routeMatch->getParam('controller');
        $module     = $this->routeMatch->getParam('__NAMESPACE__');

        $controller = explode('\\', $controller);
        $module     = explode('\\', $module);
        if($module[0] === '' && count($controller) === 3) {
            $module[0] = $controller[0];
        }

        return $module[0];
    }

    public function getController()
    {
        if($this->routeMatch == null) return false;

        $controller = $this->routeMatch->getParam('controller');
        $controller = explode('\\', $controller);
        return array_pop($controller);
    }

    public function getAction()
    {
        if($this->routeMatch == null) return false;

        return $this->routeMatch->getParam('action');
    }

    /**
     * 管理员状态
     * @param $state
     * @return mixed
     */
    public function adminState($state)
    {
        $adminState = Common::state($this->translator, 2);

        return $adminState[$state];
    }

    /**
     * 货币状态
     * @param $state
     * @return mixed
     */
    public function currencyState($state)
    {
        $currencyState = Common::state($this->translator, 2);

        return $currencyState[$state];
    }

    /**
     * 图片附件设置信息
     * @param $name
     * @return mixed|string[]|null
     */
    public function uploadIni($name)
    {
        return Common::configValue($name);
    }

    /**
     * 系统设置地图状态
     * @param $name
     * @return mixed|string[]|null
     */
    public function mapConfig($name)
    {
        return Common::configValue($name, 'config');
    }

    /**
     * 获取顶部自定义菜单
     * @return array|\Laminas\Config\Config|mixed
     */
    public function topMenuArray()
    {
        return Common::readConfigFile('topMenu');
    }

    /**
     * 自提点地图状态
     * @param $name
     * @return bool
     */
    public function selfLocationMapState($name)
    {
        $mapConfig = Common::configValue($name, 'config');
        if (
            empty($mapConfig['map_key'])
            || !isset($mapConfig['map_state'])
            || $mapConfig['map_state'] != 1
            || !isset($mapConfig['self_location_map_state'])
            || $mapConfig['self_location_map_state'] != 1) return false;
        return true;
    }

    /**
     * 国际电话区号状态
     * @param $state
     * @return mixed
     */
    public function phoneAreaState($state)
    {
        $phoneAreaState = Common::state($this->translator, 2);

        return $phoneAreaState[$state];
    }

    /**
     * 自提点状态
     * @param $state
     * @return mixed
     */
    public function selfLocationState($state)
    {
        $locationState = Common::state($this->translator, 2);

        return $locationState[$state];
    }

    /**
     * 自提点核销员状态
     * @param $state
     * @return mixed
     */
    public function selfLocationMemberState($state)
    {
        $memberState = Common::state($this->translator, 2);

        return $memberState[$state];
    }

    /**
     * 配送状态
     * @param $state
     * @return mixed
     */
    public function deliveryState($state)
    {
        $deliveryState = Common::state($this->translator, 2);

        return $deliveryState[$state];
    }

    /**
     * 支付状态
     * @param $state
     * @return mixed
     */
    public function paymentState($state)
    {
        $paymentState = Common::state($this->translator, 2);

        return $paymentState[$state];
    }

    /**
     * 支付方式显示范围
     * @param $data
     * @return string
     */
    public function paymentShow($data)
    {
        $showArray = Common::paymentShowArea($this->translator);

        $checkedArray   = $data['checked'] ?? [];
        $show           = [];
        if(is_array($checkedArray) && !empty($checkedArray)) {
            foreach ($checkedArray as $value) {
                if(isset($showArray[$value])) $show[] = $showArray[$value];
            }
        }

        return empty($show) ? (!empty($data) ? $this->translator->translate('暂未设置') : $this->translator->translate('智能匹配')) : implode(',', $show);
    }

    /**
     * 获取扩展的url信息
     * @return array|\Laminas\Config\Config
     */
    public function extendAdminUrlArray()
    {
        if (file_exists('data/moduleData/Plugin/adminUrl.ini')) return Factory::fromFile('data/moduleData/Plugin/adminUrl.ini');
        return [];
    }

    /**
     * 扩展form
     * @param $extendForm
     * @return string
     */
    public function showExtendForm($extendForm)
    {
        $extendFormHtml = '';
        foreach ($extendForm['formExtend'] as $formInputValue) {
            $extendFormHtml .= '<div class="form-group">';
            $extendFormHtml .= '<label class="col-sm-2 control-label">'.$formInputValue['inputTitle'].'</label>';
            $extendFormHtml .= '<div class="col-sm-'.$formInputValue['classSpanNum'].'"'.(isset($formInputValue['style']) ? ' '.$formInputValue['style'] : '').'>';

            if (isset($formInputValue['type'])) {
                if ($formInputValue['type'] == 'checkbox') {
                    $extendFormHtml .= '<div class="checkbox"><label>';
                    $extendFormHtml .= $this->getView()->formElement($extendForm['form']->get($formInputValue['inputName']));
                    $extendFormHtml .= $this->getView()->formElementErrors($extendForm['form']->get($formInputValue['inputName']), ['class'=>'error-message']);
                    $extendFormHtml .= $this->translator->translate('启用');
                    $extendFormHtml .= '</label></div>';
                }
            } elseif (!empty($formInputValue['inputName'])) {
                $extendFormHtml .= $this->getView()->formElement($extendForm['form']->get($formInputValue['inputName']));
                $extendFormHtml .= $this->getView()->formElementErrors($extendForm['form']->get($formInputValue['inputName']), ['class'=>'error-message']);
            }

            $staticBody = '';
            if (isset($formInputValue['staticBody']) && !empty($formInputValue['staticBody'])) {
                $staticBody = '<p class="form-control-static">'.$formInputValue['staticBody'].'</p>';
            }

            $extendFormHtml .= !empty($formInputValue['inputName']) ? '</div>'.$staticBody : $staticBody.'</div>';


            if (isset($formInputValue['helpUrl'])) {
                $extendFormHtml .= '<a href="'.$formInputValue['helpUrl']['url'].'" target="_blank" class="btn btn-info btn-sm"><i class="fa fa-info-circle"></i> '.$formInputValue['helpUrl']['title'].'</a>';
            }

            $extendFormHtml .= '</div>';
        }

        return $extendFormHtml;
    }

    /**
     * 获取国际电话区号
     * @param $areaCode
     * @return int
     */
    public function getAreaPhoneCode($areaCode)
    {
        return '+'.Common::areaPhoneCode($areaCode);
    }
}